package com.yoshino.leetcode.improve40.eighteenth;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum = 0;

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        // 中序后继节点
        // 二叉搜索树
        // p.val > root.val：结点应该在该root.right（相等也在此区间
        // 其余 p.val < root.val：结点应该是root或root.left
        int val = p.val;
        TreeNode res = null;
        while (root != null) {
            if (root.val > val) {
                res = root;
                root = res.left;
            } else {
                root = root.right;
            }
        }
        return res;
    }

    public TreeNode convertBST(TreeNode root) {
        // 当前结点的值 为右子树的和 + 本结点值
        // 遍历右子树
        if (root == null) {
            return root;
        }
        // 逆向中序
        convertBST(root.right);
        sum += root.val;
        root.val = sum;
        convertBST(root.left);
        return root;
    }
}